package _02_链表;

public class _234_回文链表 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
		head.next.next.next.next = new ListNode(1);

        _234_回文链表 obj = new _234_回文链表();
        System.out.println(obj.isPalindrome(head));

        System.out.println(head);
    }


    public boolean isPalindrome(ListNode head) {
        // 找出中间节点
        ListNode mid = findMid(head);
        // 翻转链表，从中间节点来说
        ListNode reverseHeader = reverse(mid.next);

        while (reverseHeader != null) {
            if (reverseHeader.val != head.val) {
                return false;
            }
            reverseHeader = reverseHeader.next;
            head = head.next;
        }
        return true;
    }

    // 翻转链表
    private ListNode reverse(ListNode node) {
        ListNode newHead = null;
        while (node != null) {
            ListNode temp = node.next;
            node.next = newHead;
            newHead = node;
            node = temp;
        }
        return newHead;
    }

    // 利用中间快慢指针，寻找中间节点
    private ListNode findMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


}
